package com.zksk.portal.service.invoice.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksk.common.core.domain.R;
import com.zksk.common.security.utils.SecurityUtils;
import com.zksk.mbg.admin.domain.Member;
import com.zksk.mbg.admin.domain.MemberInvoice;
import com.zksk.mbg.admin.domain.MemberInvoiceRecord;
import com.zksk.mbg.admin.mapper.MemberInvoiceMapper;
import com.zksk.portal.mapper.invoice.InvoiceDao;
import com.zksk.portal.service.invoice.MemberInvoiceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberInvoiceServiceImpl extends ServiceImpl<MemberInvoiceMapper, MemberInvoice> implements MemberInvoiceService {

   @Autowired
   private InvoiceDao invoiceDao;


    @Override
    public R saveMemberInvoice(MemberInvoiceRecord memberInvoiceRecord) {
        Long memberId = memberInvoiceRecord.getMemberId();
        QueryWrapper<MemberInvoice> queryWrapper = new QueryWrapper<MemberInvoice>()
                .eq(memberId!=null,"member_id",memberId);
        MemberInvoice memberInvoice = invoiceDao.selectOne(queryWrapper);
        // 新增
        if (memberInvoice==null){
            MemberInvoice memberInvoiceInsert = new MemberInvoice();
            MemberInvoice memberInvoice1 = buildMemberInvoiceObj(memberInvoiceInsert, memberInvoiceRecord);
            memberInvoice1.setCreateBy(SecurityUtils.getUsername());
            invoiceDao.insert(memberInvoice1);
        } else{
            MemberInvoice memberInvoice1 = buildMemberInvoiceObj(memberInvoice, memberInvoiceRecord);
            memberInvoice1.setUpdateBy(SecurityUtils.getUsername());
            invoiceDao.updateById(memberInvoice1);
        }
        // 编辑
        return R.ok(memberInvoice,"保存发票信息成功");
    }

    private MemberInvoice buildMemberInvoiceObj(MemberInvoice memberInvoice, MemberInvoiceRecord memberInvoiceRecord){
        memberInvoice.setMemberId(memberInvoiceRecord.getMemberId());//企业id
        memberInvoice.setAddress(memberInvoiceRecord.getAddress());//企业地址
        memberInvoice.setPhone(memberInvoiceRecord.getPhone());//企业电话
        memberInvoice.setTRNumber(memberInvoiceRecord.getTRNumber());//纳税人识别号
        memberInvoice.setOpenBank(memberInvoiceRecord.getOpenBank());//开户行名称
        memberInvoice.setBankAccount(memberInvoiceRecord.getBankAccount());//开户行账号
        memberInvoice.setEmail(memberInvoiceRecord.getEmail());//电子邮箱
        memberInvoice.setRecipient(memberInvoiceRecord.getRecipient());//收件人
        memberInvoice.setRecipientAddr(memberInvoiceRecord.getRecipientAddr());//收件人地址
        memberInvoice.setRecipientPhone(memberInvoiceRecord.getRecipientPhone());//收件人联系电话
        return memberInvoice;
    }
}
